﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace jlinkDemo
{
    internal class JLinkLoader
    {
        // 定义 DLL 路径
        private const string JLinkDll = "lib/JLink_x64.dll"; // JLinkARM.dll或 JLink_x64.dll
        [DllImport(JLinkDll, EntryPoint = "JLINK_Open",CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
        public static extern int JLINK_Open();

        //[DllImport(JLinkDll, EntryPoint = "JLINK_SelectFamily",CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
        //public static extern int JLINK_SelectFamily([MarshalAs(UnmanagedType.LPStr)] string sFamily);

        //[DllImport(JLinkDll, EntryPoint = "JLINK_SetChipName",CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
        //public static extern int JLINK_SetChipName([MarshalAs(UnmanagedType.LPStr)] string sChipName);

        // 设置目标芯片型号
        [DllImport(JLinkDll, EntryPoint = "JLINK_ExecCommand",CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
        public static extern int JLINK_ExecCommand(string command, StringBuilder buffer, int bufferSize);

        [DllImport(JLinkDll, EntryPoint = "JLINK_TIF_Select",CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
        public static extern int JLINK_TIF_Select(int interfaceType);

        [DllImport(JLinkDll, EntryPoint = "JLINK_SetSpeed",CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
        public static extern int JLINK_SetSpeed(int speed);

        [DllImport(JLinkDll, EntryPoint = "JLINK_DownloadFile",CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
        public static extern int JLINK_DownloadFile(string filePath, uint addr);

        // 复位函数
        [DllImport(JLinkDll,CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
        public static extern int JLINKARM_Reset();

        [DllImport(JLinkDll, EntryPoint = "JLINK_Go",CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
        public static extern int JLINK_Go();

        // 关闭 J-Link 连接
        [DllImport(JLinkDll,CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
        public static extern int JLINKARM_Close();

        // 其他需要的JLINKARM_XXX函数...
    }
}
